package sg.edu.nus.iss.phoenix.schedule.controller;

import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.util.Calendar;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;



import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sg.edu.nus.iss.phoenix.core.controller.FCUtilities;
import sg.edu.nus.iss.phoenix.schedule.delegate.ScheduleDelegate;
import sg.edu.nus.iss.phoenix.schedule.entity.ProgramSlot;
import sg.edu.nus.iss.phoenix.schedule.entity.Schedule;
import sg.edu.nus.iss.phoenix.schedule.service.DateUtil;
import sg.edu.nus.iss.phoenix.user.entity.User;
/**
 * 
 * @author Ramprasad, Karthic Kumar, Gayathri
 *
 */
@WebServlet("/ScheduleController/*")
public class ScheduleController extends HttpServlet{
	private static final long serialVersionUID = 1794890911621565515L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		try {
			processRequest(request, response);
		} catch (Exception e) {
			e.printStackTrace();
			RequestDispatcher temp = request.getRequestDispatcher("/pages/exception.jsp");
			temp.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
			try {
				processRequest(request, response);
			} catch (Exception e) {
				e.printStackTrace();
				RequestDispatcher temp = request.getRequestDispatcher("/pages/exception.jsp");
				temp.forward(request, response);
			}
	}
	
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String selection = FCUtilities.stripPath(request.getPathInfo())
				.toLowerCase();
		if(!(request.getSession().getAttribute("user")==null)){
			
		
		int choice=0;
		if(selection.equalsIgnoreCase("copyschedule"))
			choice = 1;
		if(selection.equalsIgnoreCase("createSchedule"))		
			choice = 2;
		if(selection.equalsIgnoreCase("modifySchedule"))
			choice = 3;
		if(selection.equalsIgnoreCase("deleteSchedule"))
			choice = 4;
		if(selection.equalsIgnoreCase("loadPresenter"))
			choice = 5;
		if(selection.equalsIgnoreCase("loadProducer"))
			choice = 6;
		if(selection.equalsIgnoreCase("loadProgram"))
			choice = 7;
		
		switch (choice) {
		case 1:
		{			
			ScheduleDelegate sd1 = new ScheduleDelegate();
						
			String fromDateString = request.getParameter("fromdate");
			DateFormat formater = new SimpleDateFormat("dd-MM-yyyy");  
			java.util.Date parsedUtilDate = formater.parse(fromDateString);  
			java.sql.Date sqltDate= new java.sql.Date(parsedUtilDate.getTime());

			String toDateString = request.getParameter("todate");			
			java.util.Date parsedUtilDate1 = formater.parse(toDateString);  
			java.sql.Date sqltDate1= new java.sql.Date(parsedUtilDate1.getTime());		
						
			Map<Date, Schedule> copiedWeeklySchedule = sd1.CopyWeeklySchedule(sqltDate, sqltDate1);
			
			request.getSession().setAttribute("weeklySchedule", copiedWeeklySchedule);
			request.getSession().setAttribute("daysOfWeek", DateUtil.getDays());
			request.getSession().setAttribute("allTimeSlots", DateUtil.getAllTimings());
			request.setAttribute("date", toDateString);
			RequestDispatcher rd2 = request.getRequestDispatcher("/controller/loadschedule");
			rd2.forward(request, response);
		}
		case 2:
		{
			ScheduleDelegate schDelg2 = new ScheduleDelegate();
			Schedule schedule1 = new Schedule();
			ProgramSlot programSlot = new ProgramSlot();
			programSlot.setProgramName(request.getParameter("programName"));
			String date = request.getParameter("selecteddate");
			
			request.getSession().setAttribute("date", date);
			programSlot.setDateOfProgram(DateUtil.convertProgramDateFormat(request.getParameter("date")));
			programSlot.setDuration(request.getParameter("duration"));			
			programSlot.setStartTime(programSlot.getDateOfProgram()+" "+ request.getParameter("time"));
			User presenter = new User();
			presenter.setName(request.getParameter("presentername"));
			presenter.setId(request.getParameter("presenterid"));
			programSlot.setPresenter(presenter);
			User producer = new User();
			producer.setName(request.getParameter("producername"));
			producer.setId(request.getParameter("producerid"));
			programSlot.setProducer(producer);
			
			Calendar c1 = Calendar.getInstance();
			c1.setTime(DateUtil.convertStringTodate(programSlot.getStartTime()));
			c1.add(Calendar.MINUTE, 1);
			Calendar c = Calendar.getInstance();
			c.setTime(DateUtil.convertStringTodate(programSlot.getStartTime()));
			
			System.out.println("given date in pgm"+ c.getTime());
			String newTime = programSlot.getDuration();
			String[] tokens = newTime.split("[:]");
			int min = (Integer.parseInt(tokens[0]) * 60)+ Integer.parseInt(tokens[1]);
			System.out.println("given minutes"+ min);
			c.add(Calendar.MINUTE, min-1);
			System.out.println("added date"+ c.getTime());
			request.setAttribute("errorMessage","");
			
			try
			{
			schDelg2.validateToSaveSchedule(c1.getTime(), c.getTime());
			schDelg2.validateProgramSlot(programSlot);
			
			}
			catch (Exception e)
			{
				System.err.println("Error:"+ e.getMessage());
				request.setAttribute("errorMessage",e.getMessage());
				RequestDispatcher rd2 = request.getRequestDispatcher("/pages/crudschedule.jsp");
				rd2.forward(request, response);
				break;
			}
			
			
			
			if((null != request.getParameter("programid")) && Integer.parseInt(request.getParameter("programid")) != 0)
			{
				programSlot.setProgramSlotId(Integer.parseInt(request.getParameter("programid")));
				schDelg2.modifyProgramSlot(programSlot);
			}
			else
			schDelg2.createProgramSlot(programSlot);
			RequestDispatcher rd2 = request.getRequestDispatcher("/ReviewSelectScheduledProgramController/loadschedule");
			rd2.forward(request, response);
			break;
		}
		case 3:
		{
			ScheduleDelegate schDelg3 = new ScheduleDelegate();
			Schedule schedule2 = new Schedule();
			schedule2 = (Schedule) request.getAttribute("");
			schDelg3.modifySchedule(schedule2);
			RequestDispatcher rd3 = request.getRequestDispatcher("/pages/searchschedule.jsp");
			rd3.forward(request, response);
			break;
		}
		case 4: 
		{
			ScheduleDelegate schDelg4 = new ScheduleDelegate();
			//Schedule schedule3 = new Schedule();
			//schedule3 = (Schedule) request.getAttribute("");
			String date = request.getParameter("selecteddate");
			
			request.getSession().setAttribute("date", date);
			if(request.getParameter("deleteid") != null)
			schDelg4.deleteProgramSlot(Integer.parseInt(request.getParameter("deleteid")));
			RequestDispatcher rd4 = request.getRequestDispatcher("/ReviewSelectScheduledProgramController/loadschedule");
			rd4.forward(request, response);
			break;
		}
		case 5: 
		{
			ScheduleDelegate schDelg4 = new ScheduleDelegate();
			Schedule schedule3 = new Schedule();
			schedule3 = (Schedule) request.getAttribute("");
			schDelg4.deleteSchedule(schedule3);
			RequestDispatcher rd4 = request.getRequestDispatcher("/pages/searchschedule.jsp");
			rd4.forward(request, response);
			break;
		}case 6: 
		{
			ScheduleDelegate schDelg4 = new ScheduleDelegate();
			Schedule schedule3 = new Schedule();
			schedule3 = (Schedule) request.getAttribute("");
			schDelg4.deleteSchedule(schedule3);
			RequestDispatcher rd4 = request.getRequestDispatcher("/pages/searchschedule.jsp");
			rd4.forward(request, response);
			break;
		}case 7: 
		{
			ScheduleDelegate schDelg4 = new ScheduleDelegate();
			Schedule schedule3 = new Schedule();
			schedule3 = (Schedule) request.getAttribute("");
			schDelg4.deleteSchedule(schedule3);
			RequestDispatcher rd4 = request.getRequestDispatcher("/pages/searchschedule.jsp");
			rd4.forward(request, response);
			break;
		}
		}
		}else{
			RequestDispatcher rd = request.getRequestDispatcher("controller/pages/login.jsp");
			rd.forward(request, response);
		}
	}
}
